package com.nannybear.Controller;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;
import com.nannybear.R;
/**
 * \brief Controller of the health Screen
 * \author Benjamin LANCINOT
 * \date 4-05-2015
 */

/********************************* COPYRIGHT *********************************
 * Copyright (c) 2015, Audrey LOISEAU and Benjamin LANCINOT.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *************************************************************************************/

public class HealthController {
    /********** DECLARATIONS **********/
    // Class
    private ViewPuppeteer viewPuppeteer;

    /************ METHODS ************/
    /**
     * \brief Constructor
     * \param viewPuppeteer The ViewPuppeteer
     */
    public HealthController(ViewPuppeteer viewPuppeteer) {
        this.viewPuppeteer = viewPuppeteer;
        viewPuppeteer.getmActivity().getHealthScreen().setmWeight(viewPuppeteer.getmActivity().getYoda().retrievefromJSON("weight"));
        viewPuppeteer.getmActivity().getHealthScreen().setmSize(viewPuppeteer.getmActivity().getYoda().retrievefromJSON("size"));
    }

    /**
     * \brief Initialization of interface and creation of listener
     * \param gender The gender of the baby
     */
    public void buildHealthBook(final String gender) {
        this.viewPuppeteer.getmActivity().getHealthScreen().setTitle((TextView) viewPuppeteer.getmActivity().findViewById(R.id.health_title));
        this.viewPuppeteer.getmActivity().getHealthScreen().setChangeCurve_button((ImageButton) viewPuppeteer.getmActivity().findViewById(R.id.health_nextCurve));
        this.viewPuppeteer.getmActivity().getHealthScreen().setBaby_gender((ImageView) viewPuppeteer.getmActivity().findViewById(R.id.baby_gender));
        this.viewPuppeteer.getmActivity().getHealthScreen().setWarning_neutral((TextView) viewPuppeteer.getmActivity().findViewById(R.id.warning_neutral));

        this.viewPuppeteer.getmActivity().getHealthScreen().setAge_up((ImageButton) viewPuppeteer.getmActivity().findViewById(R.id.age_up));
        this.viewPuppeteer.getmActivity().getHealthScreen().setAge_down((ImageButton) viewPuppeteer.getmActivity().findViewById(R.id.age_down));
        this.viewPuppeteer.getmActivity().getHealthScreen().setUnit_up((ImageButton) viewPuppeteer.getmActivity().findViewById(R.id.month_up));
        this.viewPuppeteer.getmActivity().getHealthScreen().setUnit_down((ImageButton) viewPuppeteer.getmActivity().findViewById(R.id.month_down));
        this.viewPuppeteer.getmActivity().getHealthScreen().setUnit((TextView) viewPuppeteer.getmActivity().findViewById(R.id.health_month));
        this.viewPuppeteer.getmActivity().getHealthScreen().setAge((TextView) viewPuppeteer.getmActivity().findViewById(R.id.health_dataAge));

        this.viewPuppeteer.getmActivity().getHealthScreen().setData((TextView) viewPuppeteer.getmActivity().findViewById(R.id.health_data));
        this.viewPuppeteer.getmActivity().getHealthScreen().setData_text((EditText) viewPuppeteer.getmActivity().findViewById(R.id.health_editData));
        this.viewPuppeteer.getmActivity().getHealthScreen().setData_unit((TextView) viewPuppeteer.getmActivity().findViewById(R.id.data_unit));
        this.viewPuppeteer.getmActivity().getHealthScreen().setAdd_button((Button) viewPuppeteer.getmActivity().findViewById(R.id.health_valid));

        this.viewPuppeteer.getmActivity().getHealthScreen().setGraph((GraphView) viewPuppeteer.getmActivity().findViewById(R.id.health_graph));
        this.viewPuppeteer.getmActivity().getHealthScreen().displayWeightCurve(gender);
        if(gender.equals("neutral")){
            this.viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.VISIBLE);
        }
        else{
            this.viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.GONE);
        }
        this.viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
        this.viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("weeks");

        this.viewPuppeteer.getmActivity().getHealthScreen().setWeight(true);

        // Listening buttons
        this.viewPuppeteer.getmActivity().getHealthScreen().getChangeCurve_button().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if(viewPuppeteer.getmActivity().getHealthScreen().isWeight()) {
                    viewPuppeteer.getmActivity().getHealthScreen().getChangeCurve_button().setImageResource(R.drawable.weight_btn);
                    viewPuppeteer.getmActivity().getHealthScreen().getData().setText("Height :");
                    viewPuppeteer.getmActivity().getHealthScreen().getData_unit().setText("cm");
                    viewPuppeteer.getmActivity().getHealthScreen().getTitle().setText("Height curve");
                    viewPuppeteer.getmActivity().getHealthScreen().setWeight(false);

                    viewPuppeteer.getmActivity().getYoda().savetoJSON(viewPuppeteer.getmActivity().getHealthScreen().getmWeight(),"weight");
                    viewPuppeteer.getmActivity().getHealthScreen().setmSize(viewPuppeteer.getmActivity().getYoda().retrievefromJSON("size"));
                    viewPuppeteer.getmActivity().getHealthScreen().displaySizeCurve(gender);
                    if(gender.equals("neutral")){
                        viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.VISIBLE);
                    }
                    else{
                        viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.GONE);
                    }
                }else{
                    viewPuppeteer.getmActivity().getHealthScreen().getChangeCurve_button().setImageResource(R.drawable.height_btn);
                    viewPuppeteer.getmActivity().getHealthScreen().getData().setText("Weight :");
                    viewPuppeteer.getmActivity().getHealthScreen().getData_unit().setText("kg");
                    viewPuppeteer.getmActivity().getHealthScreen().getTitle().setText("Weight curve");
                    viewPuppeteer.getmActivity().getHealthScreen().setWeight(true);
                    viewPuppeteer.getmActivity().getYoda().savetoJSON(viewPuppeteer.getmActivity().getHealthScreen().getmSize(),"size");
                    viewPuppeteer.getmActivity().getHealthScreen().setmWeight(viewPuppeteer.getmActivity().getYoda().retrievefromJSON("weight"));
                    viewPuppeteer.getmActivity().getHealthScreen().displayWeightCurve(gender);

                    if(gender.equals("neutral")){
                        viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.VISIBLE);
                    }
                    else{
                        viewPuppeteer.getmActivity().getHealthScreen().getWarning_neutral().setVisibility(View.GONE);
                    }
                }
            }
        });
        this.viewPuppeteer.getmActivity().getHealthScreen().getAge_up().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText().toString().equals("years")){
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) < 3) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) + 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                    }
                }else if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText().toString().equals("months")){
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) < 36) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) + 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                    }
                }else{
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) < 144) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) + 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                    }
                }
            }
        });
        this.viewPuppeteer.getmActivity().getHealthScreen().getAge_down().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText().toString().equals("years")){
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) > 0) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) - 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("3");
                    }
                }else if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText().toString().equals("months")){
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) > 0) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) - 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("36");
                    }
                }else{
                    if(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) > 0) {
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText(String.valueOf(Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) - 1));
                    }else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("144");
                    }
                }
            }
        });
        this.viewPuppeteer.getmActivity().getHealthScreen().getUnit_up().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                       if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "weeks"){
                           viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("months");
                           if(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString().matches("[0-9]+")) {
                               if (Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) > 36) {
                                   viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                               }
                           }
                       }else if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "months"){
                           viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("years");
                           if(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString().matches("[0-9]+")) {
                               if(Integer.valueOf(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) > 3) {
                                   viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                               }
                           }
                       }else{
                           viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("weeks");
                       }

            }
        });
        this.viewPuppeteer.getmActivity().getHealthScreen().getUnit_down().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "weeks"){
                    viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("years");
                }
                else if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "months"){
                    viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("weeks");
                }
                else{
                    viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("months");
                }
            }
        });
        viewPuppeteer.getmActivity().getHealthScreen().getData_text().setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    if(viewPuppeteer.getmActivity().getHealthScreen().getData_text().getText().toString().equals("\n") || viewPuppeteer.getmActivity().getHealthScreen().getData_text().getText().toString() == "" || viewPuppeteer.getmActivity().getHealthScreen().getData_text().getText().toString() == null ) {
                        Toast.makeText(viewPuppeteer.getmActivity(), "Data is unknown, please write it again", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        viewPuppeteer.getmActivity().getHealthScreen().getAdd_button().setVisibility(View.VISIBLE);
                    }
                    // close the keyboard
                    InputMethodManager imm = (InputMethodManager) viewPuppeteer.getmActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(viewPuppeteer.getmActivity().getHealthScreen().getData_text().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                }
                return false;
            }
        });
        this.viewPuppeteer.getmActivity().getHealthScreen().getAdd_button().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int age;
                float data;
                if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "years") {
                    age = Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) * 48;
                }
                else if (viewPuppeteer.getmActivity().getHealthScreen().getUnit().getText() == "months") {
                    age = Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString()) * 4;
                }
                else {
                    age = Integer.parseInt(viewPuppeteer.getmActivity().getHealthScreen().getAge().getText().toString());
                }
                data= Float.parseFloat(viewPuppeteer.getmActivity().getHealthScreen().getData_text().getText().toString());
                viewPuppeteer.getmActivity().getHealthScreen().addAData(age, data);
                viewPuppeteer.getmActivity().getHealthScreen().getAge().setText("0");
                viewPuppeteer.getmActivity().getHealthScreen().getUnit().setText("weeks");
                viewPuppeteer.getmActivity().getHealthScreen().getAdd_button().setVisibility(View.GONE);
                viewPuppeteer.getmActivity().getHealthScreen().getData_text().setText("");

            }
        });
        viewPuppeteer.getmActivity().getHealthScreen().getSerie().setOnDataPointTapListener(new OnDataPointTapListener() {

             @Override
            public void onTap(Series series, DataPointInterface dataPoint) {
                if(viewPuppeteer.getmActivity().getHealthScreen().isWeight()) {
                    displayPopUp(viewPuppeteer.getmActivity().getHealthScreen().getmWeight().indexOf(dataPoint), true);
                }else {
                    displayPopUp(viewPuppeteer.getmActivity().getHealthScreen().getmSize().indexOf(dataPoint), false);
                }
            }
        });
    }


    /**
     * \brief Display a pop up to delete a data
     * \param index Index of the item
     * \param isWeight  True if it is a data of weight, else it is a data of height
     */
    private void displayPopUp(final int index,final boolean isWeight){
            final AlertDialog popUp = new AlertDialog.Builder(this.viewPuppeteer.getmActivity().getWindow().getContext()).create();

            popUp.setTitle("Remove data");
            popUp.setMessage("Are you sure you want to delete this data ?");

                popUp.setButton(DialogInterface.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        popUp.cancel();
                    }
                });
                popUp.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(isWeight) {
                            viewPuppeteer.getmActivity().getHealthScreen().getmWeight().remove(index);
                            viewPuppeteer.getmActivity().getHealthScreen().getSerie().resetData(viewPuppeteer.getmActivity().getHealthScreen().getmWeight().toArray(new DataPoint[viewPuppeteer.getmActivity().getHealthScreen().getmWeight().size()]));
                            viewPuppeteer.getmActivity().getYoda().savetoJSON(viewPuppeteer.getmActivity().getHealthScreen().getmWeight(),"weight");
                        }else {
                            viewPuppeteer.getmActivity().getHealthScreen().getmSize().remove(index);
                            viewPuppeteer.getmActivity().getHealthScreen().getSerie().resetData(viewPuppeteer.getmActivity().getHealthScreen().getmSize().toArray(new DataPoint[viewPuppeteer.getmActivity().getHealthScreen().getmSize().size()]));
                            viewPuppeteer.getmActivity().getYoda().savetoJSON(viewPuppeteer.getmActivity().getHealthScreen().getmSize(),"size");
                        }
                        viewPuppeteer.getmActivity().getHealthScreen().changeYAxis(isWeight);
                        popUp.cancel();
                    }
                });
            popUp.setIcon(0);
            popUp.show();
    }
}
